﻿using ChuanYe.IBLL;
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using ChuanYe.Models;
using ChuanYe.Models.Model;
using ChuanYe.Commom;
using Newtonsoft.Json.Linq;
using System.Web.Http.Cors;
using System.Web.Http;

namespace SJPlatForm.Web.Controllers
{
    [EnableCors("*", "*", "*")]
    public class DocumentInfosController : BaseApiController
    {
        [Dependency]
        public IDocumentInfosBLL n_bll { get; set; }

        [Dependency]
        public ISms_SendInfoBLL m_bll { get; set; }

        /// <summary>
        /// 获取全部部门
        /// </summary>
        /// <returns></returns>
        public List<Departments> DepartmentsIsSend()
        {
            try
            {
                return n_bll.DepartmentsIsSend();
            }
            catch (Exception ex)
            {
                Log.Error("DocumentInfosController", ex.ToString());
                return new List<Departments>();
            }
        }
        /// <summary>
        /// 发送公文
        /// </summary>
        /// <param name="obj">发布人:PublishPerson,公文名：Title，公文内容：Content，情况类别：DocumentType，发布单位ID：PublishDepID，发布单位名称：PublishDepName，接收单位信息：InceptDepInfos 格式：单位ID，单位名称|单位ID，单位名称，是否发送短信：IsSMS，短信内容：SmsInfo，附件内容：InfosCommAttachs</param>
        /// <returns></returns>
        public int DocumentInfosCreate(dynamic obj)
        {
            try
            {
                int result = 0;
                DocumentInfos DInfo = new DocumentInfos();
                DInfo.publishDep = obj.PublishDepID;
                DInfo.PublishCode = GetLoginInfo(obj.key.ToString()).UserCode;
                DInfo.PublishPerson = obj.PublishPerson;
                DInfo.Title = obj.Title;
                DInfo.Content = obj.Content;
                DInfo.DocumentType = obj.DocumentType;
                DInfo.IsView = false;
                DInfo.PublishDate = DateTime.Now;
                DInfo.PublishDepName = obj.PublishDepName;
                DInfo.IsSMS = Convert.ToInt32(obj.IsSMS);
                DInfo.IsOverTime = "0";

                List<DocumentAttachs> DAttachs = new List<DocumentAttachs>();
                if (obj.InfosCommAttachs != null)
                {
                    DAttachs = ((JArray)obj.InfosCommAttachs)
                   .Select(x => new DocumentAttachs
                   {
                       FileName = (string)x["FileName"],
                       FilePath = (string)x["FilePath"],
                       FileSize = (decimal)x["FileSize"],
                   }).ToList();
                }

                Sms_SendInfo DSms = new Sms_SendInfo();
                if (DInfo.IsSMS == 1)
                {
                    DSms.IsAchieved = false;
                    DSms.IsSafety = false;
                    DSms.SafetyCode = Guid.NewGuid().ToString();
                    DSms.SendDate = DateTime.Now;
                    DSms.Sender = obj.PublishPerson;
                    DSms.SenderCode = GetLoginInfo(obj.key.ToString()).UserCode;
                    DSms.SmsInfo = obj.SmsInfo;
                }

                string InceptDepInfos = obj.InceptDepInfos;
                string[] InceptDepInfosArr = InceptDepInfos.Split('|');
                foreach (string InceptDepInfo in InceptDepInfosArr)
                {
                    string[] InceptDepInfoArr = InceptDepInfo.Split(',');
                    DInfo.InceptDep = Convert.ToInt32(InceptDepInfoArr[0]);
                    DInfo.InceptDepName = InceptDepInfoArr[1];
                    result += n_bll.DocumentInfosCreate(DInfo, DAttachs, DSms);
                    
                }
                if (result > 0)
                {
                    Log.Info(obj.key.ToString(), "发送公文", "公文发送成功！");
                }
                //2019/02/20 增加需求 选择大区下有公文短信的和用户进行发送信息




                //发送外部短信
                string odInfos = obj.OutsideDepInfos;
                string[] odInfoArray = odInfos.Split('|');
                if (odInfoArray != null && odInfoArray.Length > 0)
                {
                    foreach (var item in odInfoArray)
                    {
                        if (!string.IsNullOrEmpty(item))
                        {
                            string[] od = item.Split(',');
                            Sms_SendInfo model = new Sms_SendInfo();
                            model.IsAchieved = false;
                            model.SendDate = DateTime.Now;
                            model.SmsInfo = obj.SMSMessage;
                            model.Sender = obj.PublishPerson;
                            model.SenderCode = GetLoginInfo(obj.key.ToString()).UserCode;
                            model.SafetyCode = Guid.NewGuid().ToString();
                            model.MobileCode = od[0];
                            model.Receiver = od[1];
                            m_bll.CreateSms_SendInfo(model);
                        }
                    }
                }

                return result;
            }
            catch (Exception ex)
            {
                Log.Error("DocumentInfosController", ex.ToString());
                return -1;
            }
        }
        /// <summary>
        /// 已发送公文
        /// </summary>
        /// <param name="obj">部门ID：ToDepID，关键字：Title，接收状态：IsView，时间：Time 0：全部，1：一个月内，2：3个月内，3：6个月内，4：1年内， 页数：page，行数：rows</param>
        /// <returns></returns>
        public DocumentInfosSendResult DocumentInfosGetSend(dynamic obj)
        {
            try
            {
                DocumentInfosSendSearch search = new DocumentInfosSendSearch();
                search.ToDepID = Convert.ToInt32(obj.ToDepID);
                search.DepID = GetLoginInfo(obj.key.ToString()).DepID;
                search.Title = obj.Title;
                string IsView = obj.IsView;
                switch (IsView)
                {
                    case "0":
                        search.IsView = false;
                        break;
                    case "1":
                        search.IsView = true;
                        break;
                    case "2":
                        search.IsView = null;
                        break;
                }
                string Time = obj.Time;
                search.endTime = ValueConvert.EndTimeConvert(DateTime.Now);
                switch (Time)
                {
                    case "0":
                        search.stateTime = Common.ConfigHelper.StateTime;
                        break;
                    case "1":
                        search.stateTime = Convert.ToDateTime(DateTime.Now.AddMonths(-1).ToShortDateString() + " 00:00:00");
                        break;
                    case "2":
                        search.stateTime = Convert.ToDateTime(DateTime.Now.AddMonths(-3).ToShortDateString() + " 00:00:00");
                        break;
                    case "3":
                        search.stateTime = Convert.ToDateTime(DateTime.Now.AddMonths(-6).ToShortDateString() + " 00:00:00");
                        break;
                    case "4":
                        search.stateTime = Convert.ToDateTime(DateTime.Now.AddYears(-1).ToShortDateString() + " 00:00:00");
                        break;
                }
                search.OverTime = Common.ConfigHelper.DocumentInfosTime;
                search.stateTime = search.stateTime.AddSeconds(1);
                GridPager Pager = new GridPager();
                Pager.page = obj.page == null ? 1 : Convert.ToInt32(obj.page);
                Pager.rows = obj.rows == null ? 10 : Convert.ToInt32(obj.rows);

                var result= n_bll.DocumentInfosGetSend(search, Pager);

                //2018/09/21 需求调整 IsOverTime 0与空互换
                if (result != null && result.DocumentInfosList != null)
                {
                    for (int i = 0; i < result.DocumentInfosList.Count; i++)
                    {
                        if (string.IsNullOrEmpty(result.DocumentInfosList[i].IsOverTime))
                        {
                            result.DocumentInfosList[i].IsOverTime = "0";
                        }
                        else if (result.DocumentInfosList[i].IsOverTime == "0")
                        {
                            result.DocumentInfosList[i].IsOverTime = string.Empty;
                        }
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                Log.Error("DocumentInfosController", ex.ToString());
                return new DocumentInfosSendResult();
            }
        }
        /// <summary>
        /// 市局公文查询
        /// </summary>
        /// <param name="obj">开始时间：stateTime，结束时间：endTime，关键字：Title，页数：page，行数：rows</param>
        /// <returns></returns>
        public DocumentInfosReceiveResult DocumentInfosReceiveList(dynamic obj)
        {
            try
            {
                DocumentInfosReceiveSearch search = new DocumentInfosReceiveSearch();
                search.stateTime = obj.stateTime==""?new DateTime(): obj.stateTime;
                search.stateTime = search.stateTime.AddSeconds(1);
                search.endTime = obj.endTime == "" ? DateTime.Now : obj.endTime;
                search.endTime = ValueConvert.EndTimeConvert(search.endTime);
                search.DepID = GetLoginInfo(obj.key.ToString()).DepID;
                search.Title = obj.Title==null?"": obj.Title;
                GridPager Pager = new GridPager();
                Pager.page = obj.page == null ? 1 : Convert.ToInt32(obj.page);
                Pager.rows = obj.rows == null ? 10 : Convert.ToInt32(obj.rows);
                return n_bll.DocumentInfosReceive(search, Pager);
            }
            catch (Exception ex)
            {
                Log.Error("DocumentInfosController", ex.ToString());
                return new DocumentInfosReceiveResult();
            }
        }
        /// <summary>
        /// 获取公文查询公文详情
        /// </summary>
        /// <param name="obj">公文ID：ID</param>
        /// <returns></returns>
        public DocumentAllInfosModel DocumentInfosGetByBatch(dynamic obj)
        {
            try
            {
                DocumentInfosGetByBatchSearch model = new DocumentInfosGetByBatchSearch();
                model.ID = Convert.ToInt32(obj.ID);
                return n_bll.DocumentInfosGetByBatch(model);
            }
            catch (Exception ex)
            {
                Log.Error("DocumentInfosController", ex.ToString());
                return new DocumentAllInfosModel();
            }
        }
        /// <summary>
        /// 获取公文详情
        /// </summary>
        /// <param name="obj">公文ID:ID</param>
        /// <returns></returns>
        public DocumentAllInfosModel DocumentInfosGetByID(dynamic obj)
        {
            try
            {
                return n_bll.DocumentInfosGetByID(Convert.ToInt32(obj.ID));
            }
            catch (Exception ex)
            {
                Log.Error("DocumentInfosController", ex.ToString());
                return new DocumentAllInfosModel();
            }
        }
        /// <summary>
        /// 删除公文
        /// </summary>
        /// <param name="obj">公文ID:ID</param>
        /// <returns></returns>
        public int DocumentInfosDelete(dynamic obj)
        {
            try
            {
                int result= n_bll.DocumentInfosDelete(Convert.ToInt32(obj.ID));
                if (result > 0)
                {
                    Log.Info(obj.key.ToString(), "已发公文", "公文删除成功！");
                }
                return result;
            }
            catch (Exception ex)
            {
                Log.Error("DocumentInfosController", ex.ToString());
                return -1;
            }
        }
        /// <summary>
        /// 删除附件
        /// </summary>
        /// <param name="obj">附件ID:ID</param>
        /// <returns></returns>
        public int DocumentAttachsDelete(dynamic obj)
        {
            try
            {
                int result = n_bll.DocumentAttachsDelete(Convert.ToInt32(obj.ID));
                if (result > 0)
                {
                    Log.Info(obj.key.ToString(), "已发公文", "附件删除成功！");
                }
                return result;
            }
            catch (Exception ex)
            {
                Log.Error("DocumentInfosController", ex.ToString());
                return -1;
            }
        }
        /// <summary>
        /// 接收公文
        /// </summary>
        /// <param name="obj">公文ID：ID，收件人：InceptPerson</param>
        /// <returns></returns>
        public int DocumentInfosReceive(dynamic obj)
        {
            try
            {
                DocumentInfosModel model = new DocumentInfosModel();
                model.ID = Convert.ToInt32(obj.ID);
                model.InceptPerson = obj.InceptPerson;
                model.IsView = true;
                model.InceptDate = DateTime.Now;
                model.OverTime = Common.ConfigHelper.DocumentInfosTime;
                string result= n_bll.DocumentInfosReceive(model);
                if (result != "失败")
                {
                    Log.Info(obj.ID.ToString(), "公文接收", "公文接收成功！");
                }
                return result != "失败" ? 1 :0;
            }
            catch (Exception ex)
            {
                Log.Error("DocumentInfosController", ex.ToString());
                return 0;
            }
        }
        /// <summary>
        /// 区县公文接收
        /// </summary>
        /// <param name="obj">时间：Time 0：全部，1：一个月内，2：3个月内，3：6个月内，4：1年内， 关键字：Title，页数：page，行数：rows</param>
        /// <returns></returns>
        public DocumentInfosWaitReceiveResult DocumentInfosWaitReceive(dynamic obj)
        {
            try
            {
                DocumentInfosWaitReceiveSearch search = new DocumentInfosWaitReceiveSearch();
                string Time = obj.Time;
                search.endTime = ValueConvert.EndTimeConvert(DateTime.Now);
                switch (Time)
                {
                    case "0":
                        search.stateTime = Common.ConfigHelper.StateTime;
                        break;
                    case "1":
                        search.stateTime = Convert.ToDateTime(DateTime.Now.AddMonths(-1).ToShortDateString() + " 00:00:00");
                        break;
                    case "2":
                        search.stateTime = Convert.ToDateTime(DateTime.Now.AddMonths(-3).ToShortDateString() + " 00:00:00");
                        break;
                    case "3":
                        search.stateTime = Convert.ToDateTime(DateTime.Now.AddMonths(-6).ToShortDateString() + " 00:00:00");
                        break;
                    case "4":
                        search.stateTime = Convert.ToDateTime(DateTime.Now.AddYears(-1).ToShortDateString() + " 00:00:00");
                        break;
                }
                search.Title = obj.Title;
                search.DepID = GetLoginInfo(obj.key.ToString()).DepID;
                search.OverTime = Common.ConfigHelper.DocumentInfosTime;
                GridPager Pager = new GridPager();
                Pager.page = obj.page == null ? 1 : Convert.ToInt32(obj.page);
                Pager.rows = obj.rows == null ? 10 : Convert.ToInt32(obj.rows);
                return n_bll.DocumentInfosWaitReceive(search, Pager);
            }
            catch (Exception ex)
            {
                Log.Error("DocumentInfosController", ex.ToString());
                return new DocumentInfosWaitReceiveResult();
            }
        }
        /// <summary>
        /// 区县已收公文
        /// </summary>
        /// <param name="obj">时间：Time 0：全部，1：一个月内，2：3个月内，3：6个月内，4：1年内， 关键字：Title，页数：page，行数：rows</param>
        /// <returns></returns>
        public DocumentInfosReceivedResult DocumentInfosReceived(dynamic obj)
        {
            try
            {
                DocumentInfosReceivedSearch search = new DocumentInfosReceivedSearch();
                string Time = obj.Time;
                search.endTime = ValueConvert.EndTimeConvert(DateTime.Now);
                switch (Time)
                {
                    case "0":
                        search.stateTime = Common.ConfigHelper.StateTime;
                        break;
                    case "1":
                        search.stateTime = Convert.ToDateTime(DateTime.Now.AddMonths(-1).ToShortDateString() + " 00:00:00");
                        break;
                    case "2":
                        search.stateTime = Convert.ToDateTime(DateTime.Now.AddMonths(-3).ToShortDateString() + " 00:00:00");
                        break;
                    case "3":
                        search.stateTime = Convert.ToDateTime(DateTime.Now.AddMonths(-6).ToShortDateString() + " 00:00:00");
                        break;
                    case "4":
                        search.stateTime = Convert.ToDateTime(DateTime.Now.AddYears(-1).ToShortDateString() + " 00:00:00");
                        break;
                }
                search.Title = obj.Title;
                search.DepID = GetLoginInfo(obj.key.ToString()).DepID;
                GridPager Pager = new GridPager();
                Pager.page = obj.page == null ? 1 : Convert.ToInt32(obj.page);
                Pager.rows = obj.rows == null ? 10 : Convert.ToInt32(obj.rows);
                return n_bll.DocumentInfosReceived(search, Pager);
            }
            catch (Exception ex)
            {
                Log.Error("DocumentInfosController", ex.ToString());
                return new DocumentInfosReceivedResult();
            }
        }

        /// <summary>
        /// 获取未读公文总数和超时公文数据信息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public dynamic GetUnReadAndReceived(dynamic obj)
        {
            try
            {
                int depID= GetLoginInfo(obj.key.ToString()).DepID;
                int unReadCount=n_bll.GetUnReadDocument(depID);
                var timeOutData = n_bll.GetUnReceivedDocument(depID);
                var unReceivedList = timeOutData.DocumentInfosList.Select(s => new { s.ID, s.Title,s.PublishDate }).ToList();
                var result = new { UnReadCount=unReadCount, UnReceivedList= unReceivedList  };
                return result;
            }
            catch (Exception ex)
            {
                return null; 
            }
        }

        public string Options()
        {
            return null; // HTTP 200 response with empty body
        }
    }
}